/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.avj.g17.chat.server;

import com.avj.g17.chat.common.ChatAPI;
import com.avj.g17.chat.common.ClientCallBack;
import com.avj.g17.chat.common.model.Client;
import com.avj.g17.chat.common.model.Message;
import com.avj.g17.chat.common.model.NotificationMsg;
import com.avj.g17.chat.common.model.User;
import com.avj.g17.chat.server.util.XMLFunctions;
import java.awt.event.KeyEvent;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

/**
 *
 * @author hainn
 */
public class ServerGUI extends javax.swing.JFrame {

    public ClientCallBack clientCallBack = null;
    public Map<User, Message> messages;
    private List<String> listUserOnline = null;

    /**
     * Creates new form ClientGUI
     */
    public ServerGUI() throws RemoteException, MalformedURLException {
        initComponents();
        start();
        messages = new HashMap<User, Message>();
        listUserOnline = new ArrayList<String>();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSeparator1 = new javax.swing.JSeparator();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtText = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        btnSend = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JSeparator();
        jScrollPane3 = new javax.swing.JScrollPane();
        txtMsg = new javax.swing.JTextArea();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        txtText.setColumns(20);
        txtText.setRows(5);
        jScrollPane1.setViewportView(txtText);

        jLabel1.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
        jLabel1.setText("Server");

        btnSend.setText("Send");
        btnSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSendActionPerformed(evt);
            }
        });

        txtMsg.setColumns(2);
        txtMsg.setRows(1);
        txtMsg.setTabSize(5);
        txtMsg.setToolTipText("Enter message");
        txtMsg.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtMsgKeyPressed(evt);
            }
        });
        jScrollPane3.setViewportView(txtMsg);

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnSend, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(49, 49, 49))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 315, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 315, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addGap(48, 48, 48)
                            .addComponent(jLabel1))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 315, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(103, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 251, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 10, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btnSend, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 53, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSendActionPerformed
        try {
            // TODO add your handling code here:
            NotificationMsg msg = new NotificationMsg(NotificationMsg.NEW_MESSAGE);
            clientCallBack.notifyClient(msg);

        } catch (RemoteException ex) {
            Logger.getLogger(ServerGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btnSendActionPerformed

    private void txtMsgKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtMsgKeyPressed
        // TODO add your handling code here:
        int key = evt.getKeyCode();
        if (key == KeyEvent.VK_ENTER) {
            btnSendActionPerformed(null);
        }
    }//GEN-LAST:event_txtMsgKeyPressed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ServerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ServerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ServerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ServerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    new ServerGUI().setVisible(true);
                } catch (RemoteException ex) {
                    Logger.getLogger(ServerGUI.class.getName()).log(Level.SEVERE, null, ex);
                } catch (MalformedURLException ex) {
                    Logger.getLogger(ServerGUI.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    private void start() throws RemoteException, MalformedURLException {
        ChatAPI chatAPI = new ChatImpl();
        LocateRegistry.createRegistry(1080);
        Naming.rebind("rmi://localhost:1080/ChatServer", chatAPI);
        System.out.println("server dang chay");
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnSend;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JTextArea txtMsg;
    private javax.swing.JTextArea txtText;
    // End of variables declaration//GEN-END:variables

    public class ChatImpl extends UnicastRemoteObject implements ChatAPI {

        public ChatImpl() throws RemoteException {
        }

        @Override
        public void sendMessage(Message message) throws RemoteException {
            if (message != null) {

                messages.put(message.getSender(), message);

                txtText.append(message.getSender().getUserName()
                        + ": "
                        + message.getMessage());
                txtText.append("\n");

            } else {

                System.out.println("K co message");
            }
        }

        @Override
        public Message receiveMessage() throws RemoteException {
            Message message = new Message(
                    new User("han"),
                    new User("hai"),
                    txtMsg.getText());
            if (message.getMessage() != null) {
                txtText.append(message.getSender().getUserName()
                        + ": "
                        + message.getMessage());
                txtText.append("\n");
                txtMsg.setText("");
                messages.put(message.getSender(), message);
            }

            return message;
        }

        @Override
        public void registerChatClient(Client client) throws RemoteException {
        }

        @Override
        public boolean login(String username, String password) throws RemoteException {
            try {
                XMLFunctions xmlf = new XMLFunctions();
                Document doc = xmlf.loadXMLFile("data.xml");

                String xquery = "//user[@username='" + username + "' and @password='" + password + "']";
                NodeList list = xmlf.getNodesByXpath(xquery, doc);
                if (list != null) {
                    listUserOnline.add(username);
                    return true;
                }
                return false;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }

        @Override
        public boolean logout(String username) throws RemoteException {
            if (listUserOnline.contains(username)) {
                listUserOnline.remove(username);
                return true;
            }
            return false;
        }

        @Override
        public List<Client> getListUserOnline() throws RemoteException {
           //return listUserOnline;
            return null;
        }

        @Override
        public void signup(User user) {
            //To change body of generated methods, choose Tools | Templates.
        try {
            //load xml file

            XMLFunctions xmlf = new XMLFunctions();
            Document doc = xmlf.loadXMLFile("data.xml");
            //create element
            Element node = doc.createElement("user");
            node.setAttribute("Username", ""+user.getUserName());
            node.setAttribute("password", ""+user.getPassword());
            node.appendChild(xmlf.createElementText(doc, "name", ""+user.getFullName()+""));
            node.appendChild(xmlf.createElementText(doc, "age", ""+user.getAge()+""));
            node.appendChild(xmlf.createElementText(doc, "gender", ""+user.getGender()+""));

            doc.getFirstChild().appendChild(node);
            //write xml
            xmlf.writePrettyXML(doc,"data.xml");
        } catch (Exception e) {
        }
        }

        @Override
        public Client findClient(String username) throws RemoteException {
            throw new UnsupportedOperationException("Not supported yet.");
        }

       
        
        
    }
}
